package com.infinit.easyreader.fragment;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.infinit.easyreader.Biz.PreferenceBiz;
import com.infinit.easyreader.R;
import com.infinit.easyreader.entity.PreferencesSettings;
import com.infinit.easyreader.ui.AboutActivity;
import com.infinit.easyreader.ui.FontActivity;

import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;

import app.minimize.com.seek_bar_compat.SeekBarCompat;
import butterknife.Bind;
import butterknife.ButterKnife;

public class SettingsFragment extends Fragment {


    @Bind(R.id.fontSetting)
    ImageButton fontSetting;
    @Bind(R.id.brightSetting)
    ImageButton brightSetting;
    @Bind(R.id.sbSettings)
    SeekBarCompat sbSettings;
    @Bind(R.id.autoReadSetting)
    ImageButton autoReadSetting;
    @Bind(R.id.settingsAbout)
    LinearLayout settingsAbout;
    @Bind(R.id.settingsClearCache)
    RelativeLayout settingsClearCache;
    File cacheDir;
    @Bind(R.id.tvCacheLength)
    TextView tvCacheLength;
    @Bind(R.id.llBrightness)
    LinearLayout llBrightness;
    private PreferencesSettings settings;
    private PreferenceBiz mPreferenceBiz;
    private long fileLength;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_settings, container, false);
        ButterKnife.bind(this, view);
        fileLength = 0;
        mPreferenceBiz = new PreferenceBiz(getActivity());
        settings = mPreferenceBiz.readPreferences();
        autoReadSetting.setImageResource(R.drawable.circle);
        if (!settings.isAutoRead()) {
            autoReadSetting.setImageResource(R.drawable.circle_unchecked);
        }
        cacheDir = getActivity().getCacheDir();

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                caculateCache(cacheDir);
                BigDecimal cacheSize = new BigDecimal(fileLength);
                DecimalFormat format = new DecimalFormat();
                format.applyPattern("#0.0");
                String size = format.format(cacheSize.divide(new BigDecimal(1024 * 1024), BigDecimal.ROUND_FLOOR));
                size += " MB";
                tvCacheLength.setText(size);
            }
        });
        setListeners();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    /**
     * 设置监听器
     */
    private void setListeners() {
        fontSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), FontActivity.class);
                intent.putExtra("fontFamily", settings.getFontFamily());
                startActivity(intent);
            }
        });


        brightSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //切换显示图标和亮度设置条的显示
                if (llBrightness.getVisibility() == View.VISIBLE) {
                    brightSetting.setImageResource(R.drawable.arrow_down);
                    llBrightness.setVisibility(View.GONE);
                } else {
                    llBrightness.setVisibility(View.VISIBLE);
                    sbSettings.setProgress(settings.getBrightness());
                    //设置图标样式
                    brightSetting.setImageResource(R.drawable.arrow_up);
                }
            }
        });

        autoReadSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (settings.isAutoRead()) {
                    autoReadSetting.setImageResource(R.drawable.circle_unchecked);
                    settings.setAutoRead(false);
                } else {
                    autoReadSetting.setImageResource(R.drawable.circle);
                    settings.setAutoRead(true);
                }
            }
        });

        settingsClearCache.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getActivity().runOnUiThread(new Runnable() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void run() {
                        deleteCache(cacheDir);
                        Toast.makeText(getActivity(), "缓存清理完毕!", Toast.LENGTH_SHORT).show();
                        tvCacheLength.setText(" 0.0MB");
                    }
                });
            }
        });

        sbSettings.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                settings.setBrightness(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        settingsAbout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AboutActivity.class);
                startActivity(intent);
            }
        });

    }


    /**
     * 检查缓存大小
     */

    private void caculateCache(File dir) {
        File files[] = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                caculateCache(file);
            } else {
                fileLength += file.length();
            }
        }
    }


    /**
     * 删除缓存的目录
     */

    private void deleteCache(File dir) {
        File files[] = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                deleteCache(file);
            } else {
                //noinspection ResultOfMethodCallIgnored
                file.delete();
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        mPreferenceBiz.savePreferences(settings);
    }
}



